package com.ztjava.auth.validator;

import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseValidator;
import com.ztjava.core.utiliy.RequestUtil;
import com.ztjava.core.utiliy.StringUtil;
import com.ztjava.ext.auth.annotation.UserController;

public class LoginValidator extends BaseValidator{

	@Override
	protected void validate(Controller c) {
		setShortCircuit(true);
		String portal = c.getClass().getAnnotation(UserController.class).portal().toUpperCase();
		validateRequiredString("username", Constant.MESSAGE, "请输入用户名！");
		validateRequiredString("password", Constant.MESSAGE, "请输入密码！");
		AuthUser authUser = null;
		String username = c.getPara("username","");
		if(username.indexOf("@")>-1){
			//支持邮箱登录
			authUser = AuthUser.dao.findFirst("select * from "+AuthUser.tablename+" where portal=? and email=? order by id desc limit 1",portal,username);
		}else if(username.length()==11&&StringUtil.isNumeric(username)){
			//支持手机号登录
			authUser = AuthUser.dao.findFirst("select * from "+AuthUser.tablename+" where portal=? and phone=? order by id desc limit 1",portal,username);
		}else {
			//支持用户名登录
			authUser = AuthUser.dao.findFirst("select * from "+AuthUser.tablename+" where portal=? and username=? order by id desc limit 1",portal,username);
		}
		if(authUser==null){
			addError(Constant.MESSAGE,"用户名不正确！");
		}
		if(authUser.get("password")==null){
			addError(Constant.MESSAGE,"未设置密码，无法凭借密码登陆或者需要激活账户！");
		}
		if(authUser.getStr("enable_flag").equals(Constant.F)){
			addError(Constant.MESSAGE,"账号已被停用！");
		}
		//防止密码被暴力破解
		Cache cache = Redis.use();
		String errorKey = Constant.R_PRE+portal+"_AUTH_ERROR_"+username+"_"+RequestUtil.getIp(c.getRequest());
		if(cache.getCounter(errorKey)!=null&&cache.getCounter(errorKey)>=5){
			//方便前台识别错误类型
			setErrorCode(2);
			validateCaptcha("captcha", Constant.MESSAGE, "验证码不正确！");
			setErrorCode(1);
		}
		
		if(!authUser.getStr("password").equals(HashKit.md5(c.getPara("password")).toUpperCase())){
			cache.incr(errorKey);
			cache.expire(errorKey, 3600*24);
			if(cache.getCounter(errorKey)<5){
				addError(Constant.MESSAGE,"密码错误第"+cache.getCounter(errorKey)+"次，剩余"+(5-cache.getCounter(errorKey))+"次！");
			}else {
				setErrorCode(2);
				addError(Constant.MESSAGE,"密码错误，请输入验证码重试！");
			}
		}
		
		cache.del(errorKey);
		
		c.setAttr("authUser", authUser);
	}

}
